# 移除前端相关导入
from flask import request, jsonify
import difflib
from io import BytesIO
from file_loader import smart_extract
from diff_engine import generate_diff_output
from flask import Blueprint

# 创建蓝图
diff_bp = Blueprint('diff', __name__)


@diff_bp.route('/api/compare', methods=['POST'])
def api_compare():
    # 处理文件上传
    if 'file1' in request.files and 'file2' in request.files:
        f1 = request.files['file1']
        f2 = request.files['file2']

        try:
            f1_content = BytesIO(f1.read())
            f2_content = BytesIO(f2.read())

            c1, t1, l1 = smart_extract(f1_content, f1.filename)
            c2, t2, l2 = smart_extract(f2_content, f2.filename)

            if t1 != t2:
                return jsonify({
                    'msg': '文件类型不匹配',
                    'code': 2,
                    'data': {}
                }), 200
            old_text = "\n".join(c1)
            new_text = "\n".join(c2)
        except Exception as e:
            return jsonify({
                'msg': str(e),
                'data': {},
                'code': 2
            }), 200
    # 处理文本比较    
    else:
        data = request.get_json()
        old_text = data.get('old_text', '')
        new_text = data.get('new_text', '')

    # 统一获取diff_only参数
    diff_only = request.args.get('diff_only', 'false').lower() == 'true'

    # 计算相似度和差异输出
    similarity = difflib.SequenceMatcher(None, old_text, new_text).ratio()
    rendered_old, rendered_new = generate_diff_output(
        old_text.splitlines(), new_text.splitlines(), diff_only, l1 if 'file1' in request.files else 'text'
    )

    return jsonify({
        "data": {'similarity': similarity,
                 'rendered_old': rendered_old,
                 'rendered_new': rendered_new},
        "code": 1,
        "msg": ""
    })
